<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require './application/controllers/pc_controller.php';

class Widget_edit extends PC_controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('Projectmodel','m_project',true);
		$this->load->model('Widgetmodel','m_widget',true);
		$this->load->model('Frameworkmodel','m_framework',true);
		$this->load->model('Templatemodel','m_template',true);
		$this->load->model('Codemodel','m_code',true);
	}

	public function index($widget_id = false){
		if($widget_id === false) show_404();
		$widget = $this->m_widget->getWidget($widget_id);
		if(empty($widget)) show_404();
		$project = $this->m_project->getProject($widget['project_id']);

		$project['css'] = $this->_getProjectCss($widget['project_id']);
		$project['js'] = $this->_getProjectJs($widget['project_id']);
		if(empty($project)) show_404();

		if(!validate($project['project_commonfile'])) $project['project_commonfile'] = '[]';
		$common_file = json_decode($project['project_commonfile']);

		//add code js css by klj 2014-06-11
		$code_list = json_decode($project['project_code_ids'],true);
		if(!empty($code_list)) {
			$code_list = $this->m_code->getCodeByIds($code_list);
		}
		$code_css = '';
		$code_js = '';
		foreach ($code_list as $key => $value) {
			$code_css .= $value['code_content_css'];
			$code_js .= $value['code_content_js'];
		}
		$project['js'] = $code_js.$project['js'];
		$project['css'] = $code_css.$project['css'];

		$code = array();
		$data['widget_id'] = $widget['widget_id'];
		$data['widget_name'] = $widget['widget_name'];
		$data['project_id'] = $widget['project_id'];
		$data['project_code'] = $project['project_code'];
		$data['project_name'] = $project['project_name'];
		$data['widget_time_lastmodified'] = $widget['widget_time_lastmodified'];
		$code['widget_css'] = $widget['widget_css'];
		$code['widget_js'] = $widget['widget_js'];
		$code['widget_html'] = $widget['widget_html'];
		$code['header_html'] = '<!DOCTYPE html><html><head><meta charset="utf-8" />';
		if($project['project_type'] == PROJECT_TYPE_MOBILE){
			$code['header_html'] .= '<meta content="1 days" name="revisit-after" /><meta content="telephone=no" name="format-detection" /><meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" /><meta content="black" name="apple-mobile-web-app-status-bar-style" /><meta content="false" id="twcClient" name="twcClient" />';
		}
		$code['header_html'] .= '<script>var zmdoc = zmdoc||{};</script></head>';
		
		global $common_static_file_list;

		$this->load->library('codecompression');


		foreach ($common_static_file_list as $v) {
			if(in_array($v,$common_file)) {
				if(strpos($v, '.js') === false){
					$code['header_html'] .= '<style>'.$this->codecompression->csscompression(file_get_contents('document/common/'.$v)).'</style>';
				}else{
					$code['header_html'] .= '<script>'.$this->codecompression->jscompression(file_get_contents('document/common/'.$v)).'</script>';	
				}
			}
		}


		if(!empty($project['css']))
			$code['header_html'] .= "<style>".$this->codecompression->csscompression($project['css'])."</style>";
		if(!empty($project['js']))
			$code['header_html'] .= "<script>".$this->codecompression->jscompression($project['js'])."</script>";

		$data['code'] = $code;
		$data['permission'] = $this->m_app->outputPermission('widget_edit');
		$this->load->view('widget_edit',$data);
	}

	public function templateView($widget_name,$project_id){
		$template_id = $this->m_widget->getWidgetTemplate($widget_name,$project_id);
		if($template_id){
			redirect(base_url().'t/'.$template_id.'/1');
		}
	}

	private function _getProjectCss($project_id = false){
		//header("Content-type: text/css; charset: UTF-8");
		$item = array();
		$res = '';
		if($project_id !== false) {
			$item = $this->m_project->getProjectCss($project_id);
		}
		if(!empty($item)){
			$res .= ' '.$item['project_css_content'];
		}
		return $res;
	}

	private function _getProjectJs($project_id = false){
		//header("Content-type: text/javascript; charset: UTF-8");
		$item = array();
		if($project_id !== false) {
			$item = $this->m_project->getProjectJs($project_id);
		}
		if(!empty($item)){
			return $item['project_js_content'];
		}
		return '';
	}

	public function editWidget(){
		$this->validate->setRule('widget_id','integer');
		$this->validate->setRule('widget_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('widget_name','string');
		$this->validate->setRule('widget_name','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('widget_time_lastmodified','string');
		$this->validate->setRule('widget_time_lastmodified','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('widget_css','string');
		$this->validate->setRule('widget_css','optional');
		$this->validate->setRule('widget_css','notnull',false);
		$this->validate->setRule('widget_css','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('widget_js','string');
		$this->validate->setRule('widget_js','optional');
		$this->validate->setRule('widget_js','notnull',false);
		$this->validate->setRule('widget_js','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('widget_html','string');
		$this->validate->setRule('widget_html','optional');
		$this->validate->setRule('widget_html','notnull',false);
		$this->validate->setRule('widget_html','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$widget = $this->m_widget->getWidget($info['widget_id']);
		if(empty($widget) || $widget['widget_time_lastmodified'] != $info['widget_time_lastmodified']){
			
			$this->response->setDetail($this->lang->line('error_edited'));
			$this->response->responseExit();
		}

		$info['user_id'] = $this->m_app->getCurrentUserId();
		$info['widget_time_lastmodified'] = NOW;
		$this->m_widget->editWidget($info['widget_id'],$info);
		$history_info = array(
			'widget_id' => $info['widget_id'],
			'user_id' => $info['user_id'],
			'widget_history_time_create' => NOW,
			'widget_history_css' => $info['widget_css'],
			'widget_history_js' => $info['widget_js'],
			'widget_history_html' => $info['widget_html'],
		);
		$this->m_widget->createWidgetHistory($history_info);
		//$this->m_template->updateTemplateLastmodifiedByWidget($widget['project_id'],$info['widget_name'],$info['user_id']);

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->setAddon(array('widget_time_lastmodified'=>NOW));
		$this->response->responseExit();
	}

	public function getProjectFileList(){
		$this->validate->setRule('project_code','string');
		if(!$this->validate->run($this->input->post())){
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		//$file_pos = UPLOAD_PATH.$project['project_code'].'/'.$info['project_file']['name'][$i];
		$info = $this->validate->getResult();
	
		$images = @scandir(UPLOAD_PATH.$info['project_code']);
		$list = array();
		if($images) {
			foreach ($images as $img) {
				$file = UPLOAD_PATH.$info['project_code'].'/'.$img;
				if(is_dir($file)) continue;

				$size = @getimagesize($file);
				
				if($img=='sprite.png') continue;
				$list[] = array(
					'project_file_name' => $img,
					'project_file_path' => $file,
					'project_file_widthheight' => $size?$size[3]:'',
					'project_file_html' => ($img=='sprite.png')?
					'<span style="color:#800;">background:transparent url('.str_replace(dirname(BASEPATH),'',UPLOAD_PATH).$info['project_code'].'/'.$img.') no-repeat 0 0;</span>':'<img src="'.str_replace(dirname(BASEPATH),'',UPLOAD_PATH).$info['project_code'].'/'.$img.'" '.$size[3].' />',
					'project_file_time_lastmodified' => date("Y-m-d H:i:s", filemtime($file)),
					'project_file_url' => UPLOAD_URL.$info['project_code'].'/'.$img,
					'project_file_size' => round((filesize($file) / 1024), 2),
				);

			}
		}
		

		usort($list, array("Widget_edit", "custom_sort"));
     	

	

		
		$count = count($list);

		$this->response->setSuccess();
		$this->response->setItems($list);
		$this->response->setTotalCount($count);
		$this->response->responseExit();
	}
	// Define the custom sort function
	static function custom_sort($a,$b) {
	        return $a['project_file_time_lastmodified']<$b['project_file_time_lastmodified'];
	}

	public function addImage($project_id = 0){
		if(!$this->m_app->initFolder()){
			$this->response->setDetail($this->lang->line('error_update'));
			$this->response->responseExit();
		}

		$project = $this->m_project->getProject($project_id);
		if(empty($project)) {
			$this->response->setDetail('项目错误');
			$this->response->responseExit();
		}
		$old = umask(0);
		@mkdir(UPLOAD_PATH.$project['project_code'].'/',0777,true);
		umask($old);

		$existed_sprite = $this->m_project->getProjectSpriteList($project_id);
		$existed_sprite = reindexArray($existed_sprite,'sprite_name');

		$filename = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : 'a.jpg');
		$path = $project['project_code'].'/'.$filename;
		$file_pos = UPLOAD_PATH.$path;
		file_put_contents($file_pos,file_get_contents('php://input'));
		
		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}

	public function removeProjectFile(){
		$this->validate->setRule('project_file_path','string');
		$this->validate->setRule('project_file_path','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		
		if(file_exists($info['project_file_path'])){
			unlink($info['project_file_path']);
		}
		

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}
}
/* End of file widget_edit.php */
/* Location: ./application/controllers/widget_edit.php */
